import { Book } from "../entity/Book";
import { getRepository, Like } from 'typeorm';

class BookServer {
  
  // 添加图书
  addBook(bookDate: Book) {
    const bookRepository = getRepository(Book);
    const book = bookRepository.create(bookDate);
    return bookRepository.save(book);
  }

  // 根据 id 删除图书
  delBook(id: string) {
    const bookRepository = getRepository(Book);
    return bookRepository.delete(id)
  }

  // 修改图书
  updateBook(id: string, data: Book) {
    const bookRepository = getRepository(Book);
    return bookRepository.update(id ,data)
  }

  // 图书库存数量减 1 （根据图书 id 实现）
  bookStockDecrement(id:string) {
    const bookRepository = getRepository(Book);
    return bookRepository.manager.decrement(Book, { id }, 'stock', 1);
  }

  // 图书库存数量加 1 （根据图书 id 实现）
  bookStockIncrement(id:string) {
    const bookRepository = getRepository(Book);
    return bookRepository.manager.increment(Book, { id }, 'stock', 1);
  }

  // 查询所有图书
  findAllBooks() {
    const bookRepository = getRepository(Book);
    return bookRepository.find();
  }

  // 根据 id 查询图书
  findBookById(id: string) {
    const bookRepository = getRepository(Book);
    return bookRepository.findOne(id)
  }

  // 根据图书名称关键词查询图书
  findBookByNameKey(key: string) {
    const bookRepository = getRepository(Book);
    return bookRepository.find({
      where: {
        bookname: Like(`%${key}%`)
      }
    })
  }

  // 根据图书类别关键词查询图书
  findBookByTypeKey(key:string) {
    const bookRepository = getRepository(Book);
    return bookRepository.find({
      where: {
        booktype: Like(`%${key}%`)
      }
    })
  }

  // 根据图书作者关键词查询图书
  findBookByAuthorKey(key:string) {
    const bookRepository = getRepository(Book);
    return bookRepository.find({
      where: {
        author: Like(`%${key}%`)
      }
    })
  }
}

export default new BookServer()